<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>



    <script>



        function observer(obj, cb) {
            const res = {};
            for (let key in obj) {
                Object.defineProperty(res, key, {
                    get() {
                        return obj[key]
                    },
                    set(v) {
                        obj[key] = v;
                        // 数据修改之后，重新加入这个行为
                        cb(res);
                    }
                })
            }

            // 数据复制成功之后加入行为
            cb(res);

            return res;
        }



        const obj1 = { a: 1, b: 2 };


        const oH1 = document.querySelector('h1');

        const obj2 = observer(obj1, function (res) {
            oH1.innerHTML = res.a;
        })


        document.onclick = function () {
            obj2.a = 10;
        }


    </script>

</body>

</html>